package com.example.newhabitclock

import android.app.AlarmManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.example.newhabitclock.HabitAlarm.AlarmHelper
import com.example.newhabitclock.TimeDown.TimeDownViewModel
import com.example.newhabitclock.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    private lateinit var mBinding: ActivityMainBinding
    private val mainViewModel: MainViewModel by viewModels()
    val viewModel: TimeDownViewModel by viewModels {
        ViewModelProvider.AndroidViewModelFactory.getInstance(application)
    }
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        mBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        /*Handler(Looper.getMainLooper()).postDelayed({  //延迟2.5s 等动画结束覆盖主界面
            supportFragmentManager.commit {
                replace(R.id.fragmentContainerView,MainFragment())  //主界面入栈代替
                setReorderingAllowed(true)
                addToBackStack(null)
            }
        },2500)*/
        //最后由于BottomNavigationView没有NavController来进行点击下方icon图标进行Fragment界面切换的操作
        //所以我们在Activity中给BottomNavigationView传入一个NavController(fragmentContainerView中获取的)
        // 获取NavHostFragment并从中获取NavController
        val navHostFragment = supportFragmentManager.findFragmentById(R.id.fragmentContainerView) as NavHostFragment
        val navController = navHostFragment.navController
        mBinding.tabLayout.setupWithNavController(navController)

        /*mainViewModel.allHabits.observe(this) { habits ->
            AlarmHelper.setAlarmsForHabits(this, habits)
        }*/
        // 检查权限并设置闹钟
        checkAndRequestExactAlarmPermission()

        /*//每日凌晨重置每条习惯的打卡状态为false
        scheduleResetTask(this)*/
    }

    /*@RequiresApi(Build.VERSION_CODES.O)
    fun scheduleResetTask(context: Context) {
        val resetRequest = PeriodicWorkRequestBuilder<ResetCheckInWorker>(1, TimeUnit.DAYS)
            .setInitialDelay(calculateInitialDelay(), TimeUnit.MILLISECONDS)
            .build()
        WorkManager.getInstance(context).enqueueUniquePeriodicWork(
            "reset_check_in",
            ExistingPeriodicWorkPolicy.KEEP,
            resetRequest
        )
    }*/

    /*@RequiresApi(Build.VERSION_CODES.O)
    fun calculateInitialDelay(): Long {
        val now = LocalDateTime.now()
        val midnight = now.plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0)
        return Duration.between(now, midnight).toMillis()
    }*/

    @RequiresApi(Build.VERSION_CODES.O)
    private fun checkAndRequestExactAlarmPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
            if (!alarmManager.canScheduleExactAlarms()) {
                // 权限未授予，引导用户到设置页面
                val intent = Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM)
                intent.data = Uri.parse("package:$packageName")
                startActivity(intent)
                Toast.makeText(this, "请授予精确闹钟权限", Toast.LENGTH_LONG).show()
            } else {
                // 权限已授予，设置闹钟
                setAlarms()
            }
        } else {
            // Android 11 及以下版本，直接设置闹钟（权限已在清单中声明）
            setAlarms()
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun setAlarms() {
        mainViewModel.allHabits.observe(this) { habits ->
            AlarmHelper.setAlarmsForHabits(this, habits)
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onResume() {
        super.onResume()
        // 每次Activity恢复时检查权限
        checkAndRequestExactAlarmPermission()
    }
}